import autoinstall
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import requests
import warnings

def invest(df1,frequence,invest_money,start_time):
    '''
     定投计算
    :param df1: 数据集
    :param frequence: 定投频率
    :param invest_money: 每次定投金额
    :param start: 定投起始日期
    :return (amount,invest_log): (收益数据DataFrame，定投记录dict)
    '''
    invest_log={}#每次定投的日期记录(日期:大盘指数)
    invest_day=start_time#每次投资的时间
    invest_amount=0#总投资金额
    profile=0#总投资收益
    amount=0#账户总资产
    
    profile_log=[]#总收益日志
    invest_amount_log=[]#账户投资金额日志
    amount_log=[]#总资产日志
    Yield=[]#收益率日志
    
    for date,quote_change,index in zip(df1.index,df1['涨跌幅'],df1['收盘价']):
        profile+=quote_change*amount#计算当天收益率
        profile_log.append(profile)
        
       
        #判断是否为定投日
        if date==invest_day:
            invest_amount+=invest_money
            invest_log[invest_day]=index#记录定投当日的指数
            
            #判断7天后是否为交易日,如果不是则往后加1天直到找到交易日
            invest_day+=np.timedelta64(frequence,'D')
            flag=0
            while(True):
                if(df1[df1.index==invest_day].index==invest_day):
                    break
                else:
                    invest_day+=np.timedelta64(1,'D')
                    flag+=1
                    if(flag==100):
                        break
                        
            
        invest_amount_log.append(invest_amount)
        amount=invest_amount+profile#更新账户总资产
        amount_log.append(amount)
        try:
            Yield.append(profile/invest_amount*100)#更新收益率
        except:
            Yield.append(0)
    print("总投资：",invest_amount)
    print("总收益：",profile)
    print("收益率: ",profile/invest_amount*100,"%")
    
    over=pd.DataFrame({
        "日期":df1.index,
        "收益率":Yield,
        "账户资产":amount_log,
        "投资金额":invest_amount_log
    })
    over=over.set_index("日期")
    return over,invest_log